package com.reggie.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.ReggieApplication;
import com.reggie.config.ApplicationContextProvider;
import com.reggie.pojo.Dish;
import com.reggie.pojo.Setmeal;
import com.reggie.pojo.User;
import com.reggie.service.CategoryService;
import com.reggie.service.DishService;
import com.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.TimerTask;

/**
 * @author zhaoyuheng
 * @email 2646498606@qq.com
 * @date 2022/4/26 0:17
 * 删除多余的图片文件,以定时任务执行,
 */
//@Component
public class ClearImgTimerTask extends TimerTask {
    private final DishService dishService = (DishService) ApplicationContextProvider.getBean("dishService");
    private final SetmealService setmealService = (SetmealService) ApplicationContextProvider.getBean("setmealService");

    private final ReggieApplication reggieApplication = ApplicationContextProvider.getBean(ReggieApplication.class);

    private static String basePath;
    @Value("${reggie.path}")
    public void setBasePath(String value) {
        basePath = value;
    }

    @Override
    @Scheduled(cron = "0 0/2 *  * * ? ")//每2分钟触发一次
//    @Scheduled(cron = "0 0 12 * * ?")//每天12点触发
    public void run() {
        checkFile();
    }

    /**
     * 检查文件是否可以删除,可以删除的文件直接删除
     */
    private void checkFile() {
        File file = new File(basePath);
        //获取文件夹中的文件名
        List<String> fileNames = GetFileName.getFileName(file);
        //遍历查找图片对应数据
        for (String fileName : fileNames) {
            //构造条件查找器
            LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
            dishWrapper.eq(Dish::getImage, fileName);
            LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
            setmealWrapper.eq(Setmeal::getImage, fileName);

            //查询
            int countDish = dishService.count(dishWrapper);
            int countSetmeal = setmealService.count(setmealWrapper);
            if (countDish + countSetmeal > 0) {
                System.out.println("有对应数据");
            } else {
                deleteFolder(basePath + fileName);
                System.out.println("没有对应数据");
            }
        }
    }

    /**
     * 删除文件
     * @param fileName 文件名
     */
    private void deleteFolder(String fileName) {
        File file = new File(fileName);
        file.delete();
        System.out.println("删除成功");
    }

}
